import { state } from "../config.js";
import { boxH, boxW, currentRole } from "../index.js";
import { emit } from "../utils/scoket.js";
import { getRolePosition, setTransfrom } from "./newTransfrom.js";

//移动指令
let timer: any = {};
let lastKey = "";
export const move = (key: string) => {
  //速度频率
  if (typeof timer[key] === "number") return;
  timer[key] = setTimeout(
    () => (timer[key] = undefined),
    1000 / state.moveFrequency
  );
  const rolePosition = getRolePosition();

  switch (key) {
    case "a":
      if (rolePosition.x <= 0) return;
      rolePosition.x -= state.roleSpeed;
      currentRole.style.transform = setTransfrom(rolePosition);
      break;
    case "d":
      if (rolePosition.x >= boxW) {
        rolePosition.x = boxW;
      } else {
        rolePosition.x += state.roleSpeed;
      }
      currentRole.style.transform = setTransfrom(rolePosition);
      break;
    case "w":
      if (rolePosition.y <= 0) return;
      rolePosition.y -= state.roleSpeed;
      currentRole.style.transform = setTransfrom(rolePosition);
      break;
    case "s":
      if (rolePosition.y + 10 >= boxH) {
        rolePosition.y = boxH;
      } else {
        rolePosition.y += state.roleSpeed;
      }
      currentRole.style.transform = setTransfrom(rolePosition);
      break;
  }

  if (localStorage.role === "p1") {
    emit.p1("/key/down", { key, rolePosition });
  } else if (localStorage.role === "p2") {
    emit.p2("/key/down", { key, rolePosition });
  }
};
